import java.util.Arrays;

/**
 * @author: TTDB
 * @create: 2025/10/27
 */
public class CountingSort {
    public static void countingSort(int[] arr) {
        int max = Arrays.stream(arr).max().getAsInt();
        int min = Arrays.stream(arr).min().getAsInt();
        int range = max - min + 1;
        int[] count = new int[range];
        int[] output = new int[arr.length];

        // 计数每个元素的出现次数
        for (int num : arr) {
            count[num - min]++;
        }

        // 计数数组累加
        for (int i = 1; i < count.length; i++) {
            count[i] += count[i - 1];
        }

        // 构建排序后的数组
        for (int i = arr.length - 1; i >= 0; i--) {
            output[count[arr[i] - min] - 1] = arr[i];
            count[arr[i] - min]--;
        }

        // 将排序后的结果复制回原数组
        System.arraycopy(output, 0, arr, 0, arr.length);
    }

    public static void main(String[] args) {
        int[] arr = {4, 2, 2, 8, 3, 3, 1};
        countingSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
